using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Microsoft.Phone;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Controls.Primitives;
using System.Windows.Resources;

using System.Text;
using System.Collections;

using System.Runtime.Serialization.Json;
using System.Windows.Navigation;


namespace VISUALFINDR
{
    public partial class MainPage : PhoneApplicationPage
    {
        //The camera chooser used to capture a picture.
        CameraCaptureTask cameraCaptureTask;
        PhotoChooserTask photoChooserTask;
        bool cameFromOutside;
        bool cameraCaptureOrPhotoChooser;
        public MainPage()
        {
            InitializeComponent();

            SupportedOrientations = SupportedPageOrientation.Portrait;// | SupportedPageOrientation.Landscape;

            cameraCaptureTask = new CameraCaptureTask();
            photoChooserTask = new PhotoChooserTask();

            //Create new event handler for capturing a photo
            cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);
            photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);

            buttonVisualSearch.IsEnabled = false;
            buttonTakePicture.IsEnabled = true;

            cameraCaptureOrPhotoChooser = false;

            cameFromOutside = true;
        }

        // Take Picture
        private void buttonTakePicture_Click(object sender, RoutedEventArgs e)
        {
            App.Reset();

            cameraCaptureOrPhotoChooser = true;

            cameraCaptureTask.Show();
        }

        // Take picture initiated using the camera icon button in the textbox
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            App.Reset();

            cameraCaptureOrPhotoChooser = true;

            cameraCaptureTask.Show();
        }

        private void buttonLoadFromLibrary_Click(object sender, RoutedEventArgs e)
        {
            imageCaptured.Source = null;

            App.Reset();

            cameraCaptureOrPhotoChooser = true;

            photoChooserTask.Show();
        }

        /// <summary>
        /// Event handler for retrieving the JPEG photo stream.
        /// Also to for decoding JPEG stream into a writeable bitmap and displaying.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cameraCaptureTask_Completed(object sender, PhotoResult e)
        {
            HandlePhotoResult(e);
        }

        void photoChooserTask_Completed(object sender, PhotoResult e)
        {
            HandlePhotoResult(e);
        }

        void HandlePhotoResult(PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                App.Reset();

                //Take JPEG stream and decode into a WriteableBitmap object
                App.CapturedImage = PictureDecoder.DecodeJpeg(e.ChosenPhoto);

                // Save image.
                HistoryController.SaveToDisk(App.CapturedImage);

                //Populate image control with WriteableBitmap object.
                imageCaptured.Source = App.CapturedImage;

                buttonVisualSearch.IsEnabled = true;

                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(MakeVisualSearch);
                //MakeVisualSearch();
            }
        }

        private void buttonTestRecognised_Click(object sender, RoutedEventArgs e)
        {
            App.Reset();

            //Obtain a virtual store for application
            IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
            StreamResourceInfo sr = Application.GetResourceStream(new Uri("UploadTestImageRecognised.jpg", UriKind.Relative));

            //Take JPEG stream and decode into a WriteableBitmap object
            App.CapturedImage = PictureDecoder.DecodeJpeg(sr.Stream);

            // Save image.
            HistoryController.SaveToDisk(App.CapturedImage);

            //Populate image control with WriteableBitmap object.
            imageCaptured.Source = App.CapturedImage;

            buttonVisualSearch.IsEnabled = true;

            MakeVisualSearch();
        }

        private void buttonTestNotRecognised_Click(object sender, RoutedEventArgs e)
        {
            App.Reset();

            /*
            String jsonString = "{\"d\":{\"__type\":\"APISearchStatus:#Cortexica.API\",\"Count\":\"0\",\"Objects\":null,\"Status\":\"waiting\"}}";
            PollResponseDictionary d = new PollResponseDictionary();
            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(d.GetType());
            d = serializer.ReadObject(ms) as PollResponseDictionary;
            ms.Close();
            */

            IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
            StreamResourceInfo sr = Application.GetResourceStream(new Uri("UploadTestImageNotRecognised.jpg", UriKind.Relative));

            //Take JPEG stream and decode into a WriteableBitmap object
            App.CapturedImage = PictureDecoder.DecodeJpeg(sr.Stream);

         

            HistoryController.SaveToDisk(App.CapturedImage);

            //Collapse visibility on the progress bar once writeable bitmap is visible.
            //progressBar1.Visibility = Visibility.Collapsed;

            //Populate image control with WriteableBitmap object.
            imageCaptured.Source = App.CapturedImage;

            //Once writeable bitmap has been rendered, the crop button
            //is enabled.
            buttonVisualSearch.IsEnabled = true;

            MakeVisualSearch();
        }

        // Make Visual Search
        private void buttonVisualSearch_Click(object sender, RoutedEventArgs e)
        {
            //testing
            //App.uploadController.LatestResponse = "{\"d\":{ \"id\" : \"4319\",\"status\":\"\" } }";

            MakeVisualSearch();
        }

        void MakeVisualSearch()
        {
            App.pollingController.ForceReset();

            cameraCaptureOrPhotoChooser = false;

            NavigationService.Navigate(new Uri("/VisualSearchPage.xaml", UriKind.Relative));
        }

        void DisplayNoConnection()
        {
            //BitmapImage image = new BitmapImage(new Uri("/ImageFailedBackgroundImage.jpg", UriKind.Relative));
            //BackgroundImage.Source = image;
        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            DisplayNoConnection();
        }

        private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (textBox1.Text.Contains("\r"))
            {
                String queryString = textBox1.Text.Replace("\r","");
                textBox1.Text = queryString;
                UriBuilder fullUri = new UriBuilder("http://bing.com/search?q=" + queryString);//"&go=&form=QBLH&filt=all&qs=n&sk=&sc=8-4");
                NavigationService.Navigate(new Uri("/BingBrowserPage.xaml?url=" + fullUri, UriKind.Relative));
            }
        }

        private void hideTestUI()
        {
            buttonLoadFromLibrary.Visibility = Visibility.Collapsed;
            buttonTakePicture.Visibility = Visibility.Collapsed;
            buttonTestNotRecognised.Visibility = Visibility.Collapsed;
            buttonTestRecognised.Visibility = Visibility.Collapsed;
            buttonVisualSearch.Visibility = Visibility.Collapsed;
            imageCaptured.Visibility = Visibility.Collapsed;
        }

        private void showTestUI()
        {
            buttonLoadFromLibrary.Visibility = Visibility.Visible;
            buttonTakePicture.Visibility = Visibility.Visible;
            buttonTestNotRecognised.Visibility = Visibility.Visible;
            buttonTestRecognised.Visibility = Visibility.Visible;
            buttonVisualSearch.Visibility = Visibility.Visible;
            imageCaptured.Visibility = Visibility.Visible;
            if (App.CapturedImage != null)
            {
                imageCaptured.Source = App.CapturedImage;
                buttonVisualSearch.IsEnabled = true;
            }
        }

        private void hideOrShowTestUI()
        {
            // always show:
            showTestUI();
            /*
            if (buttonLoadFromLibrary.Visibility == Visibility.Collapsed)
            {
                showTestUI();
            }
            else
            {
                hideTestUI();
            }*/
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            hideOrShowTestUI();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //hideTestUI();
            showTestUI();

            //Gets a dictionary of query string keys and values
            IDictionary<string, string> queryStrings = this.NavigationContext.QueryString;
            string filename = string.Empty;

            //This code ensures that there is at least one key in the query string, and check if the "file" key is present.
            if (queryStrings.Count > 0 && queryStrings.ContainsKey("file"))
            {
                if (cameFromOutside && !cameraCaptureOrPhotoChooser)
                {
                    cameFromOutside = false;
                    //The value for the key "file" is filename.
                    filename = this.NavigationContext.QueryString["file"];

                    //This code appends the folder name (Incoming) to the file path. The isolated storage folder "Incoming"
                    // was specified in the Extras.xml file.         
                    filename = System.IO.Path.Combine("Incoming", filename);

                    //The following opens the file in the isolated storage folder.
                    IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();

                    if (isoStore.FileExists(filename))
                    {
                        IsolatedStorageFileStream isolatedStorageFileStream = isoStore.OpenFile(filename, FileMode.Open, FileAccess.Read);

                        App.Reset();

                        //This code decodes stream into a WriteableBitmap object and adds it to the Image control Source property.
                        App.CapturedImage = PictureDecoder.DecodeJpeg(isolatedStorageFileStream);

                        // Save image.
                        //HistoryController.SaveToDisk(e.ChosenPhoto);
                        HistoryController.SaveToDisk(App.CapturedImage);

                        //Populate image control with WriteableBitmap object.
                        imageCaptured.Source = App.CapturedImage;

                        //Once writeable bitmap has been rendered, the crop button
                        //is enabled.
                        buttonVisualSearch.IsEnabled = true;

                        isolatedStorageFileStream.Close();

                        // delete the incoming file so we dont go in here again!!!
                        isoStore.DeleteFile(filename);

                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(MakeVisualSearch);
                        //MakeVisualSearch();
                    }
                    else
                    {
                        String gotText = App.GetText();
                        if (gotText != null && gotText.Length > 0)
                            textBox1.Text = gotText;
                    }
                    //imageCaptured.Visibility = Visibility.Visible;
                }
                else
                {
                    String gotText = App.GetText();
                    if (gotText != null && gotText.Length > 0)
                        textBox1.Text = gotText;
                }
            }
            else
            {
                String gotText = App.GetText();
                if (gotText != null && gotText.Length > 0)
                    textBox1.Text = gotText;
            }
        }

    }
}